from playwright.sync_api import Page, Locator


class PageSlicer:
    def __init__(self, page: Page, title: str) -> None:
        self.slicer_box = (
            page.locator("css=[data-cp-tag=Slicer] > label")
            .filter(has_text=title)
            .locator("..")
        )
        self.select_locator = self.slicer_box.locator("css= div.el-select")
        self.page = page
        self.options_pane = self.page.locator("css=.el-popper")

    def switch_options_pane(self):
        """eq by click"""
        self.select_locator.click()

    def select_options_by_text(self, text: str):
        self.options_pane.get_by_role("listitem").filter(has_text=text).click()

    def clear_selected(self):
        self.slicer_box.locator("svg").nth(1).click()

    def get_option_values(self):
        return self.options_pane.get_by_role("listitem").all_text_contents()


class PageTable:
    def __init__(self, page: Page, debug_tag: str) -> None:
        self.table = page.locator(f"css=[data-debug-tag={debug_tag}]")

    def get_header_cells(self):
        cells = self.table.locator("css=.el-table__header").get_by_role("cell")
        return cells

    def get_rows(
        self,
    ):
        rows = self.table.locator("css=.el-table__body").get_by_role("row")
        return rows

    def get_row_values(self, row_idx: int):
        return self.get_rows().all()[row_idx].get_by_role("cell").all_text_contents()

    def get_table_col_values(self, col_idx: int):
        return list(cell.text_content() for cell in self._get_table_col(col_idx))

    def _get_table_col(self, col_idx: int):
        rows = self.get_rows()
        for row in rows.all():
            yield row.get_by_role("cell").all()[col_idx]


class PageBarEChart:
    def __init__(self, page: Page, debug_tag: str) -> None:
        self.chart_box = page.locator(f"css=[data-debug-tag={debug_tag}]")
        paths = page.query_selector_all(f"[data-debug-tag={debug_tag}] g path")
        self.bars = [path for path in paths if path.bounding_box()["height"] > 100]

    def get_locator_by_text(self, text: str):
        return self.chart_box.locator("css=text").filter(has_text=text)

    def should_has_text(self, text: str):
        self.get_locator_by_text(text).wait_for(timeout=2000)

    def should_not_has_text(self, text: str):
        self.get_locator_by_text(text).wait_for(timeout=1000, state="detached")

    def hover_bar(self, bar_idx: int):
        self.bars[bar_idx].hover()
